package com.game.share;

import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class StreamWriter {
	private static final int BUFFER_SIZE = 1024;

	DataOutputStream stream;

	public StreamWriter(OutputStream output) {
		this.stream = new DataOutputStream(output);
	}

	public void writeInt(int value) throws IOException {
		stream.writeInt(value);
	}
	
	public void writeLong(long value) throws IOException{
		stream.writeLong(value);
	}
	
	public void writeObject(Object obj) throws IOException{
		if (obj instanceof String) {
			writeString((String) obj);
		} else if (obj instanceof Integer) {
			writeInt((Integer) obj);
		}
	}

	public void writeString(String value) throws IOException {
		if (value != null) {
			byte[] data = Util.stringToByte(value);
			stream.writeInt(data.length);
			stream.write(data);
		} else {
			stream.writeInt(0);
		}
	}

	public void writePackage(IOPackage pack) throws IOException {
		writeInt(pack.getType().value());
		writeInt(pack.getData().length);
		writeData(stream, pack.getData());
	}

	private static void writeData(OutputStream out, byte[] data)
			throws IOException {
		int len = data.length;
		if (len > 0) {
			if (len < BUFFER_SIZE) {
				out.write(data);
			} else {
				writeLargeData(out, data);
			}
		}
	}

	private static void writeLargeData(OutputStream out, byte[] data)
			throws IOException {
		ByteArrayInputStream input = new ByteArrayInputStream(data);
		byte[] tmp = new byte[BUFFER_SIZE];
		int count = 0;
		while ((count = input.read(tmp)) > 0) {
			out.write(tmp, 0, count);
		}
	}
	
	public void flush(){
		try {
			stream.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void close() {
		try {
			stream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws Exception {

	}

}
